package com.ptswitch.material.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hxzon.util.DateFormatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ptswitch.material.model.common.Uzer;
import com.ptswitch.material.model.contract.Contract;
import com.ptswitch.material.model.contract.ContractItem;
import com.ptswitch.material.model.security.Role;
import com.ptswitch.material.util.security.RoleUtil;

public class ContractUtil {
    private static final Logger logger = LoggerFactory.getLogger(ContractUtil.class);
    private static final Map<String, Integer> contractCodeCache = new HashMap<String, Integer>();
    private static final Map<String, Integer> contractItemCodeCache = new HashMap<String, Integer>();

    public static void buildContractCode(Contract contract) {
        String code = DateFormatUtil.format(new Date(), "'CON-'yyMMdd-");
        Integer num = contractCodeCache.get(code);
        if (num != null) {
            num += 1;
        } else {
            num = 1;
        }
        contract.setCode(code + num);
        contractCodeCache.clear();
        contractCodeCache.put(code, num);
    }

    public static void buildContractItemCode(ContractItem contractItem) {
        String code = DateFormatUtil.format(new Date(), "'S'-DDD-");
        Integer num = contractItemCodeCache.get(code);
        if (num != null) {
            num += 1;
        } else {
            num = 1;
        }
        contractItem.setCode(code + num);
        contractItemCodeCache.clear();
        contractItemCodeCache.put(code, num);
    }

    public static List<Role> appendThisRole(Contract contract, Uzer visitor) {
        if (contract == null) {
            logger.warn("contract is null");
            return Collections.emptyList();
        }
        List<Role> roles = new ArrayList<Role>();
        if (contract.getCreater().equals(visitor)) {
            roles.add(RoleUtil.ContractCreater);
        }
        if (contract.getAuditor().equals(visitor)) {
            roles.add(RoleUtil.ContractAuditor);
        }
        if (contract.getFinancial().equals(visitor)) {

        }
        if (contract.getProduction().equals(visitor)) {

        }
        return roles;
    }
}
